import socketio

import config
from imgLoader import ImgLoader
from imgLoader.WatchingLoader import WatchingLoader
from share import img_loader_dict, watching_dict, watching_dicom_queue_dict
from type import EnumLoadDicomMode

# 创建 Socket.IO 服务器
sio = socketio.AsyncServer(
                            cors_allowed_origins='*',
                            namespace='/ct',
                            ping_timeout=60,
                            ping_interval=25
                            )



# Socket.IO 事件处理
@sio.event(namespace='/ct')
async def connect(sid, environ):
    print(f"Socket.IO client connected: {sid}")


@sio.event(namespace='/ct')
async def disconnect(sid):
    print(f"Socket.IO client disconnected: {sid}")
    client_id = sid
    if img_loader_dict.__contains__(client_id):
        img_loader: ImgLoader = img_loader_dict.get(client_id)
        img_loader = None
        img_loader_dict.pop(client_id, None)
        watch_loader: WatchingLoader = watching_dict.get(client_id)
        watch_loader.stop()
        watch_loader = None

        q = watching_dicom_queue_dict.get(client_id)
        q = None
        watching_dicom_queue_dict.pop(client_id, None)
        watching_dict.pop(client_id, None)

        print(f'断开连接，清除：client_id,{client_id}, ',watch_loader, watching_dicom_queue_dict)


@sio.event(namespace='/ct')
async def message(sid, data):
    client_id = sid
    img_loader: ImgLoader = img_loader_dict[client_id]
    await img_loader.handle_op( data)


async def send_message_to_a_client(client_id, data):
    await sio.emit('image',
                   data,
                   room=client_id,  # 指定目标客户端的 sid
                   namespace='/ct')
